package com.zxg.util.login;

import java.io.IOException;

import org.apache.commons.httpclient.HttpException;

import com.alibaba.fastjson.JSON;
import com.taobao.api.internal.util.WebUtils;
import com.zxg.util.WeixinComponent;

/**
 * 微信开放平台网站授权登陆
 * 
 * @author Administrator
 *
 */
public class WeixinLogin {

  static String appId  = "wxe52f367c1b60827c";
  static String redUrl = "http://wx.manongsoft.com/hb/index";
  static String sec    = "d44c2fe2aa627202fd849629ee641935";

  public static String getLoginUrl(WeixinComponent app) {
    String weixin = "https://open.weixin.qq.com/connect/qrconnect?appid=" + appId + "&redirect_uri=" + redUrl + "&response_type=code&scope=snsapi_login&state="
        + app.getValue() + "#wechat_redirect";
    return weixin;
  }

  public static void main(String[] args) {
    System.out.println(WeixinLogin.getLoginUrl(WeixinComponent.ZXG));
  }

  public static WeixinUser getWeixinUser(String code) {
    String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + appId + "&secret=" + sec + "&code=" + code + "&grant_type=authorization_code";
    try {
      String rtn = WebUtils.doPost(url, null, 2000, 2000);
      if (rtn != null) {
        WeixinUser wl = JSON.parseObject(rtn, WeixinUser.class);
        if (wl != null && wl.getAccess_token() != null && wl.getOpenid() != null) {
          String url2 = "https://api.weixin.qq.com/sns/userinfo?access_token=" + wl.getAccess_token() + "&openid=" + wl.getOpenid();
          rtn = WebUtils.doPost(url2, null, 2000, 2000);
          WeixinUser wl2 = JSON.parseObject(rtn, WeixinUser.class);
          wl2.setAccess_token(wl.getAccess_token());
          return wl2;
        }
      }
    } catch (HttpException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    return null;
  }
}
